package com.inspur.edp.bef.bemanager.service;

import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityErrorCodeEnum;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityException;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.collection.GspAssociationKeyCollection;
import com.inspur.edp.cef.designtime.api.element.GspAssociationKey;
import com.inspur.edp.das.commonmodel.IElementCollection;
import com.inspur.edp.das.commonmodel.IGspCommonObject;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CheckBeChildTableService {
    private static CheckBeChildTableService instance;
    private final String parentID = "parentID";

    /**
     * 校验Be存在子表，且子表parentId 字段非"ParentID"时， 不允许其他表字段为parentId
     *
     * @param containChildObjects be信息
     */
    public void checkChildTable(List<IGspCommonObject> containChildObjects) {
        if (containChildObjects == null) {
            return;
        }
        for (IGspCommonObject iGspCommonObject : containChildObjects) {
            GspAssociationKeyCollection keys = iGspCommonObject.getKeys();
            if (keys.isEmpty()) {
                continue;
            }
            GspAssociationKey key = keys.get(0);
            String parentIdId = key.getSourceElement(); // 获取parentId对应的编号
            examineElements(parentIdId, iGspCommonObject.getContainElements(), iGspCommonObject.getName());
            checkChildTable(iGspCommonObject.getContainChildObjects()); // 递归调用校验子表的子表
        }
    }

    private void examineElements(String parentIdId, IElementCollection containElements, String tableName) {
        Map<String, String> elementIdToCodeLabelIdMap = containElements.stream().collect(Collectors
                .toMap(IGspCommonField::getID, IGspCommonField::getLabelID));
        String parentIdName = elementIdToCodeLabelIdMap.get(parentIdId);
        if (parentID.equalsIgnoreCase(parentIdName)) {
            // 子表parent 标签为parentID
            return;
        }
        for (String elementLabelName : elementIdToCodeLabelIdMap.values()) {
            if (parentID.equalsIgnoreCase(elementLabelName)) {
                throw BusinessEntityException.createException(BusinessEntityErrorCodeEnum.GSP_BEMODEL_BUSINESS_ENTITY_0028, tableName);
            }
        }
    }

    public static CheckBeChildTableService getInstance() {
        if (instance == null)
            instance = new CheckBeChildTableService();
        return instance;
    }
}
